//
// Created on 2025/8/13.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "RNCNativeEngineViewComponentInstance.h"
#include <multimedia/image_framework/image/pixelmap_native.h>
#include <stdio.h>


namespace rnoh {
RNCNativeEngineViewComponentInstance::RNCNativeEngineViewComponentInstance(Context context)
    : CppComponentInstance(std::move(context)) {}

RNCNativeEngineViewComponentInstance::~RNCNativeEngineViewComponentInstance() {}

void RNCNativeEngineViewComponentInstance::onChildInserted(ComponentInstance::Shared const &childComponentInstance,
                                                           std::size_t index) {
    CppComponentInstance::onChildInserted(childComponentInstance, index);
    auto mWidth = childComponentInstance->getLayoutMetrics().frame.size.width;
}

void RNCNativeEngineViewComponentInstance::onChildRemoved(ComponentInstance::Shared const &childComponentInstance) {
    CppComponentInstance::onChildRemoved(childComponentInstance);
};

RNCEngineNode &RNCNativeEngineViewComponentInstance::getLocalRootArkUINode() { return m_EngineNode; }

void RNCNativeEngineViewComponentInstance::onPropsChanged(SharedConcreteProps const &props) {
    CppComponentInstance::onPropsChanged(props);
    if (props == nullptr) {
        return;
    }
    DLOG(INFO) << "sssss-------->onPropsChanged antiAliasing:" << props->antiAliasing;
    DLOG(INFO) << "sssss-------->onPropsChanged isTransparent:" << props->isTransparent;
    DLOG(INFO) << "sssss-------->onPropsChanged androidView:" << props->androidView;
    if (props->antiAliasing) {
        m_EngineNode.setAntiAliasing(props->antiAliasing);
    }
    if (props->isTransparent) {
        m_EngineNode.setIsTransparent(props->isTransparent);
    }
    m_EngineNode.setAndroidView(props->androidView);
}

void RNCNativeEngineViewComponentInstance::onSnapshotDataReturned(std::string data) {
    DLOG(INFO) << "jk--------> onSnapshotDataReturned 准备发送";
    if (m_eventEmitter) {
        DLOG(INFO) << "jk--------> onSnapshotDataReturned 准备发送 1";
        m_eventEmitter->onSnapshotDataReturned({data});
        DLOG(INFO) << "jk--------> onSnapshotDataReturned 已发送";
    }
};

// Base64 字符表（标准编码表）
const std::string BASE64_CHARS ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/**
 * 将二进制数据转换为 Base64 字符串（标准实现）
 * @param data 输入的二进制数据指针
 * @param len 数据长度
 * @return 编码后的 Base64 字符串
 */
std::string base64Encode(const uint8_t* data, size_t len) {
    if (data == nullptr || len == 0) {
        return "";
    }

    std::string result;
    result.reserve(((len + 2) / 3) * 4); // 预分配内存以提高性能

    for (size_t i = 0; i < len; i += 3) {
        uint32_t triple = 0;

        // 第一个字节
        triple |= (static_cast<uint32_t>(data[i]) << 16);

        // 第二个字节（如果存在）
        if (i + 1 < len) {
            triple |= (static_cast<uint32_t>(data[i + 1]) << 8);
        }

        // 第三个字节（如果存在）
        if (i + 2 < len) {
            triple |= static_cast<uint32_t>(data[i + 2]);
        }

        // 生成4个Base64字符
        result += BASE64_CHARS[(triple >> 18) & 0x3F];
        result += BASE64_CHARS[(triple >> 12) & 0x3F];

        if (i + 1 < len) {
            result += BASE64_CHARS[(triple >> 6) & 0x3F];
        } else {
            result += '=';
        }

        if (i + 2 < len) {
            result += BASE64_CHARS[triple & 0x3F];
        } else {
            result += '=';
        }
    }

    return result;
}

void RNCNativeEngineViewComponentInstance::onSnapshoting() {
    DLOG(INFO) << "jk--------> onSnapshoting 准备开始截图";

    // 初始化变量
    OH_PixelmapNative *pixelmap = nullptr;
    OH_Pixelmap_ImageInfo *imageInfo = nullptr;
    uint8_t* destination = nullptr;
    std::string base64Result = "";

    try {
        // 获取节点快照
        int32_t code = OH_ArkUI_GetNodeSnapshot(m_EngineNode.getArkUINodeHandle(), nullptr, &pixelmap);
        if (code != ARKUI_ERROR_CODE_NO_ERROR) {
            DLOG(ERROR) << "jk--------> OH_ArkUI_GetNodeSnapshot 失败: " << code;
            throw std::runtime_error("获取快照失败");
        }

        // 创建图像信息对象
        Image_ErrorCode image_ErrorCode = OH_PixelmapImageInfo_Create(&imageInfo);
        if (image_ErrorCode != IMAGE_SUCCESS) {
            DLOG(ERROR) << "jk--------> OH_PixelmapImageInfo_Create 失败:" << image_ErrorCode;
            throw std::runtime_error("创建图像信息失败");
        }

        // 获取图像信息
        image_ErrorCode = OH_PixelmapNative_GetImageInfo(pixelmap, imageInfo);
        if (image_ErrorCode != IMAGE_SUCCESS) {
            DLOG(ERROR) << "jk--------> OH_PixelmapNative_GetImageInfo 失败:" << image_ErrorCode;
            throw std::runtime_error("获取图像信息失败");
        }

        // 获取宽度
        uint32_t width;
        image_ErrorCode = OH_PixelmapImageInfo_GetWidth(imageInfo, &width);
        if (image_ErrorCode != IMAGE_SUCCESS) {
            DLOG(ERROR) << "jk--------> OH_PixelmapImageInfo_GetWidth 失败:" << image_ErrorCode;
            throw std::runtime_error("获取宽度失败");
        }

        // 获取高度
        uint32_t height;
        image_ErrorCode = OH_PixelmapImageInfo_GetHeight(imageInfo, &height);
        if (image_ErrorCode != IMAGE_SUCCESS) {
            DLOG(ERROR) << "jk--------> OH_PixelmapImageInfo_GetHeight 失败:" << image_ErrorCode;
            throw std::runtime_error("获取高度失败");
        }

        // 获取像素格式
        int32_t pixelFormat;
        image_ErrorCode = OH_PixelmapImageInfo_GetPixelFormat(imageInfo, &pixelFormat);
        if (image_ErrorCode != IMAGE_SUCCESS) {
            DLOG(ERROR) << "jk--------> OH_PixelmapImageInfo_GetPixelFormat 失败:" << image_ErrorCode;
            throw std::runtime_error("获取像素格式失败");
        }

        DLOG(INFO) << "jk--------> 图像信息 - 宽度: " << width << ", 高度: " << height << ", 像素格式: " << pixelFormat;

        // 检查图像尺寸是否有效
        if (width == 0 || height == 0) {
            DLOG(ERROR) << "jk--------> 无效的图像尺寸: " << width << "x" << height;
            throw std::runtime_error("无效的图像尺寸");
        }

        // 分配像素数据缓冲区（RGBA格式，每像素4字节）
        size_t bufferSize = width * height * 4;
        destination = static_cast<uint8_t*>(malloc(bufferSize));
        if (destination == nullptr) {
            DLOG(ERROR) << "jk--------> 内存分配失败，大小: " << bufferSize;
            throw std::runtime_error("内存分配失败");
        }

        // 读取像素数据
        image_ErrorCode = OH_PixelmapNative_ReadPixels(pixelmap, destination, &bufferSize);
        if (image_ErrorCode != IMAGE_SUCCESS) {
            DLOG(ERROR) << "jk--------> OH_PixelmapNative_ReadPixels 失败:" << image_ErrorCode;
            throw std::runtime_error("读取像素数据失败");
        }

        DLOG(INFO) << "jk--------> 成功读取像素数据，大小: " << bufferSize << " 字节";

        // 转换为Base64编码
        std::string base64Str = base64Encode(destination, bufferSize);
        if (base64Str.empty()) {
            DLOG(ERROR) << "jk--------> Base64编码失败";
            throw std::runtime_error("Base64编码失败");
        }

        // 构造完整的Data URI格式（React Native Image组件需要这种格式）
        base64Result = "data:image/png;base64," + base64Str;

        DLOG(INFO) << "jk--------> 截图成功完成 - 宽度: " << width << ", 高度: " << height
                   << ", 数据长度: " << base64Result.length() << " 字符";

    } catch (const std::exception& e) {
        DLOG(ERROR) << "jk--------> 截图过程中发生异常: " << e.what();
        base64Result = ""; // 确保返回空字符串表示失败
    }

    // 清理资源
    if (destination != nullptr) {
        free(destination);
        destination = nullptr;
    }

    if (imageInfo != nullptr) {
        OH_PixelmapImageInfo_Release(imageInfo);
    }

    if (pixelmap != nullptr) {
        OH_PixelmapNative_Release(pixelmap);
    }

    // 发送结果到React Native层
    this->onSnapshotDataReturned(base64Result);

    DLOG(INFO) << "jk--------> onSnapshoting 截图流程结束";
};

void RNCNativeEngineViewComponentInstance::handleCommand(std::string const &commandName, folly::dynamic const &args) {
    DLOG(INFO) << "sssss-------->handleCommand:" << commandName;
    if (commandName == "takeSnapshot") {
        this->onSnapshoting();
    }
};


}; // namespace rnoh
